import { createRouter, createWebHistory } from 'vue-router'
import { useAuthStore } from '@/stores/auth'

const routes = [
  {
    path: '/login',
    name: 'Login',
    component: () => import('@/views/Login.vue')
  },
  {
    path: '/',
    name: 'Chat',
    component: () => import('@/views/Chat.vue'),
    meta: { requiresAuth: true }
  }
]

const router = createRouter({
  history: createWebHistory(),
  routes
})

// 路由守卫
router.beforeEach((to, from, next) => {
  const authStore = useAuthStore()
  
  // 打印路由守卫状态，方便调试
  console.log('Route guard:', {
    to: to.path,
    from: from.path,
    isLoggedIn: authStore.isLoggedIn,
    hasToken: !!localStorage.getItem('token'),
    requiresAuth: to.meta.requiresAuth
  })
  
  // 双重检查：确保 auth store 状态与 localStorage 同步
  // 如果 localStorage 有 token 但 store 状态不对，重新初始化
  const hasToken = !!localStorage.getItem('token')
  if (hasToken && !authStore.isLoggedIn) {
    console.log('Syncing auth state from localStorage...')
    authStore.initializeAuth()
  }
  
  // 使用 store 的 isLoggedIn 状态
  const isAuthenticated = authStore.isLoggedIn
  
  if (to.meta.requiresAuth && !isAuthenticated) {
    // 需要认证但未登录，跳转到登录页
    console.log('Redirecting to login: not authenticated')
    next('/login')
  } else if (to.path === '/login' && isAuthenticated) {
    // 已登录但访问登录页，跳转到首页
    console.log('Redirecting to home: already authenticated')
    next('/')
  } else {
    next()
  }
})

export default router
